package net.dasviertel.buddylockscreen.data;

import net.dasviertel.buddylockscreen.application.BaseApplication;
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.util.Log;

public class ContactsDataManager {

	private ContentResolver contentResolver;

	private Cursor cursor;

	private static ContactsDataManager instance;

	public ContactsDataManager() {
	}

	public void init() {
		contentResolver = BaseApplication.getInstance().getApplicationContext().getContentResolver();
	}

	public ContactsObject getContactById(String searched) {
		
		ContactsObject contactsObject = new ContactsObject();
		
//		String id = "";
		
		cursor = getContactsList();

		if (cursor.getCount() > 0) {

			
			while (cursor.moveToNext()) {
		
				
				String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
				
				String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				
				if(id.equals(searched)) {
					
					contactsObject.setId(id);
					contactsObject.setName(name);
					
				}
				
				
			}

		}
		
		
		return contactsObject;
	}
	
	public ContactsObject getContactByName(String searchedContact) {

		ContactsObject contactsObject = new ContactsObject();

		cursor = getContactsList();

		if (cursor.getCount() > 0) {

			while (cursor.moveToNext()) {

				String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

				if (name.equals(searchedContact)) {

					contactsObject.setName(name);

					String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

					contactsObject.setId(id);

					if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {

						Cursor numbersCursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);

						while (numbersCursor.moveToNext()) {

							String phone = numbersCursor.getString(numbersCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

							contactsObject.getPhoneNumbers().add(phone);						
						}

						numbersCursor.close();
					}
				}
			}
		}

		return contactsObject;
	}

	public boolean numberIsChanged(String searchedContact) {

		return false;
	}

	public Cursor getContactsList() {

		return contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

	}

	public static ContactsDataManager getInstance() {

		if (instance == null) {
			instance = new ContactsDataManager();
		}
		return instance;
	}
}
